import { Button, Card, message, Popconfirm, Table } from 'antd';
import { useEffect, useState } from 'react';

import parameterService from '@/api/services/stars/parameterService';
import { Iconify } from '@/components/icon';
import TipIconButton from '@/components/icon/tooltip-icon-button';
import { datetime } from '@/utils/format-date';
import { pagination } from '@/utils/pagination';
import { hasPermission } from '@/utils/permission';

import ParameterModal from './parameter-modal';
import ParameterSearchForm from './search-form';
import { ParameterSearchFormType, ParameterType } from './type';

import { ListData, ModalProps } from '#/entity';

const DEFAULT_PARAMETER: ParameterType = { system: false, key: '', name: '' };

export default function Parameter() {
  const [tableData, setTableData] = useState<ListData<ParameterType>>({ data: [], count: 0 });
  const [searchData, setSearchData] = useState<ParameterSearchFormType>({
    page: 1,
    take: 10,
  });

  const [modalProps, setModalProps] = useState<ModalProps<ParameterType>>({
    show: false,
    title: '',
    formValue: DEFAULT_PARAMETER,
    onOk: () => {
      setModalProps((prev) => ({ ...prev, show: false }));
      setSearchData((prev) => ({
        ...prev,
        page: 1,
      }));
    },
    onCancel: () => {
      setModalProps((prev) => ({ ...prev, show: false }));
    },
  });
  const onEdit = (record: ParameterType) => {
    setModalProps((prev) => ({
      ...prev,
      show: true,
      title: '修改参数设置',
      formValue: record,
    }));
  };
  // 获取信息

  useEffect(() => {
    parameterService.getParametersList(searchData).then((res) => {
      setTableData(res);
    });
  }, [searchData]);

  const onCreate = () => {
    setModalProps((prev) => ({
      ...prev,
      show: true,
      title: '新增参数',
    }));
  };

  const onDelete = (record: ParameterType) => {
    parameterService.deleteParameter({ ids: [record.id!] }).then((res) => {
      if (res > 0) {
        message.success('删除成功');
      }
      setSearchData({ page: 1, take: searchData.take });
    });
  };
  // search
  const onReset = () => {
    setSearchData({ page: 1, take: 10 });
  };
  const onSearch = (data: ParameterSearchFormType) => {
    setSearchData({ page: 1, take: searchData.take, ...data });
  };
  const columns = [
    { title: '参数名', dataIndex: 'name', width: 200 },
    {
      title: '参数键',
      dataIndex: 'key',
      width: 150,
    },
    {
      title: '参数值',
      dataIndex: 'value',
      width: 150,
    },
    {
      title: '系统内置',
      dataIndex: 'system',
      render: (text: boolean) => {
        return text ? <span>是</span> : <span>否</span>;
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      key: 'id',
      width: 150,
      render: (text: string) => {
        return datetime(text);
      },
    },
    {
      fixed: 'right' as const,
      align: 'right' as const,
      title: <div style={{ marginRight: '18px' }}>操作</div>,
      render: (record: ParameterType) => {
        return (
          <div
            style={{
              textAlign: 'right',
              display: 'flex',
              color: 'grey',
              justifyContent: 'flex-end',
            }}
          >
            {hasPermission('STARS:PARAMETERS:UPDATE') && (
              <TipIconButton onClick={() => onEdit(record)} tipText="修改">
                <Iconify icon="solar:pen-bold-duotone" size={18} />
              </TipIconButton>
            )}
            {hasPermission('STARS:PARAMETERS:DELETE') && (
              <Popconfirm
                title="确认删除吗?"
                okText="确定"
                cancelText="取消"
                onConfirm={() => {
                  onDelete(record);
                }}
                placement="left"
              >
                <TipIconButton tipText="删除">
                  <Iconify icon="mingcute:delete-2-fill" size={18} className="text-error" />
                </TipIconButton>
              </Popconfirm>
            )}
          </div>
        );
      },
    },
  ];

  return (
    <div>
      <ParameterSearchForm onOk={onSearch} onReset={onReset} />
      <br />
      <Card
        title="参数设置"
        extra={
          <div className="flex items-center gap-2">
            {hasPermission('STARS:PARAMETERS:CREATE') && (
              <Button
                type="primary"
                // disabled={!hasPermission('SECURITY:USER:CREATE')}
                onClick={() => {
                  onCreate();
                }}
              >
                新增
              </Button>
            )}
          </div>
        }
      >
        <Table
          size="small"
          rowKey="id"
          dataSource={tableData?.data}
          columns={columns}
          scroll={{ x: 'max-content' }}
          pagination={pagination({
            page: searchData,
            onPageChange: (page, rows) => {
              setSearchData((prev) => ({
                ...prev,
                page,
                take: rows,
              }));
            },
            count: tableData?.count,
          })}
        />
        <ParameterModal {...modalProps} />
      </Card>
    </div>
  );
}
